import {ComboBox, Flex, Item, ProgressCircle} from "@adobe/react-spectrum";
import {ListLocations} from "~/lib/server";
import {useEffect, useState} from "react";

export function SelectLocation({ defaultSelectedKey = 0 }: { defaultSelectedKey?: number }) {
  const { data, error, isLoading } = ListLocations();
  const [selectedKey, setSelectedKey] = useState<string>(defaultSelectedKey?.toString() || "0");

  // 当defaultSelectedKey改变时更新selectedKey，确保0也能正确处理
  useEffect(() => {
    // 明确处理0和undefined的情况
    const newKey = defaultSelectedKey !== undefined ? defaultSelectedKey.toString() : "0";
    setSelectedKey(newKey);
  }, [defaultSelectedKey]);

  // 调试信息
  useEffect(() => {
    if (data) {
      const found = data.find(item => item.id.toString() === selectedKey);
    }
  }, [data, selectedKey]);

  // 确保位置数据包含ID为0的选项
  const processedItems = data?.map(item => ({
    ...item,
    id: item.id.toString()
  })) || [];

  // 检查是否已有ID为0的选项，如果没有则添加一个
  const hasZeroOption = processedItems.some(item => item.id === "0");
  const finalItems = hasZeroOption ? processedItems : [
    {id: "0", name: "根位置"},
    ...processedItems
  ];

  if (isLoading) {
    return (
        <Flex direction="column" gap="size-100">
          <div className="text-sm">位置</div>
          <ProgressCircle size="S" aria-label="加载位置数据中..." isIndeterminate/>
        </Flex>
    );
  }

  if (error) {
    return (
        <Flex direction="column" gap="size-100">
          <div className="text-sm">位置</div>
          <div>加载位置数据失败</div>
        </Flex>
    );
  }

  return (
    <ComboBox
      name="locationId"
      label="位置"
      items={finalItems}
      selectedKey={selectedKey}
      onSelectionChange={key => {
        console.log("选择变更为:", key);
        setSelectedKey(key as string);
      }}
      formValue="key"
    >
      {(item) => (
          <Item key={item.id}>{item.name}</Item>
      )}
    </ComboBox>
  );
}